/**
 * <b>日期：</b>2015/04/08 10:50 AM<br/>
 * <b>Copyright (c)</b> 2015 广州天健软件有限公司<br/>
 */
package com.github.kennylee26.javaee.mvc;

import com.github.kennylee26.javaee.mvc.entity.User;
import com.github.kennylee26.javaee.mvc.utils.ResourceUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * <b>类名称：</b>UserPageController<br/>
 * <b>类描述：</b>SpringMVC例子，返回页面视图。<br/>
 * <b>备注：</b><br/>
 *
 * @author kennylee <br />
 * @version 1.0.0 <br/>
 */
@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserPageController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 通过Model传递后台数据，然后通过String查找对应的视图。
     *
     * @param model Model
     * @param name  前端传递的数据。
     * @return String 视图Path
     */
    @RequestMapping(value = "/p/{name}", method = {RequestMethod.GET})
    public String view(Model model, @PathVariable("name") String name) throws IOException {
        logger.trace("name is: {}", name);
        User user = generateUserStub();
        user.setName(name);
        user.setComment("get");
        model.addAttribute("user", user);
        return "/user";
    }

    /**
     * 自己指定ModelAndView
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/mav/{name}", method = {RequestMethod.GET})
    public ModelAndView modelAndView(@PathVariable("name") String name) {
        ModelAndView mav = new ModelAndView();
        User user = generateUserStub();
        user.setName(name);
        user.setComment("modelAndView");
        mav.addObject("user", user);
        mav.setViewName("/user");
        return mav;
    }

    /**
     * 文件下载的例子
     *
     * @param id
     * @throws IOException
     */
    @RequestMapping(value = "/download/{id}", method = {RequestMethod.GET})
    public void download(@PathVariable("id") String id, HttpServletResponse response) throws IOException {
        User user = generateUserStub();
        //普通流程是根据id找出实体，然后从实体中拿到文件的path
        InputStream is = new FileInputStream(user.getAvatarPath());
        IOUtils.copy(is, response.getOutputStream());
        response.setContentType("image/png");//根据文件设置
    }

    private User generateUserStub() {
        User user = new User();
        File avatarFile = ResourceUtils.getAvatarFile();
        user.setAvatarPath(avatarFile.getAbsolutePath());
        return user;
    }

}
